package com.fecean.aabbc.netty.server.prod7;

import com.fecean.aabbc.netty.message7.MessageBuilder;
import com.fecean.aabbc.netty.message7.MessageType;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 ** 服务端心跳通道处理，目前处理是把消息原样发回给客户端
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-03-05 15:59
 * @blame Team
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyServerHeartbeatHandler extends ChannelInboundHandlerAdapter {

    /**
     ** 读取数据处理，把客户端发送过来的信息原样发送回去
     *
     * @param ctx 通道上下文
     * @param msg 读取到的数据
     * @throws Exception 处理过程中存在异常则抛出
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MessageBuilder messageBuilder = MessageBuilder.of(msg);
        if(messageBuilder.isMessage(MessageType.HEARTBEAT)){
            log.info("客户端[{}-{}]收到心跳",
                    messageBuilder.getMessage().getTenantId(),
                    messageBuilder.getMessage().getCinemaCode());
            ctx.writeAndFlush(msg);
            return;
        }
        ctx.fireChannelRead(msg);
    }
}
